import { Control } from 'react-keeper'
import DB from './../../app/db';
import StorageUtils from '../../app/storage'
import Utils from "../../utils/index";

const {MOCK_WECHAT_OPEN_ID, __LOCAL__} = require(`../../config/${ENV}.json`);

export default (callback, props)=> {

  let userInfo = StorageUtils.getUser();
  if (userInfo && userInfo.openId && userInfo.openId !== 'xxx') {
    getProprietor(userInfo, callback);
  } else {

    if (__LOCAL__) {
      DB.WechatAPI.getLocalUser({openId: MOCK_WECHAT_OPEN_ID}).then(
        function (content) {
          StorageUtils.setStorage('user', content);
          getProprietor(content, callback);
        },
        function (error) {
          alert(JSON.stringify(error));
        }
      ).catch(function (reason) {
        alert("系统错误");
      });
    } else {
      let code = Utils.GetQueryString(window.location.search, 'code');
      if (code) {
        DB.WechatAPI.getUser({code: code}).then(
          function (content) {
            StorageUtils.setStorage('user', content);
            getProprietor(content, callback);
          },
          function (error) {
            alert('缓存失效，请关闭页面重试。');
            // Control.replace('/home/my', null);
          }
        ).catch(function (reason) {
          alert("系统错误");
        });
      } else {
        alert('请在微信客户端打开。');
      }
    }
  }
}

function getProprietor(userInfo, callback) {
  if (StorageUtils.hasItemInStorage('proprietor') && StorageUtils.getStorageItem('proprietor')) {
    callback();
  } else {
    if (userInfo && userInfo.openId && userInfo.openId !== 'xxx') {
      DB.WechatAPI.getProprietorByOpenId({openId: userInfo.openId}).then(
        function (content) {
          if (content && content.id) {
            StorageUtils.updateUser({proprietorId: content.id});
            StorageUtils.setStorage('proprietor', content);
            callback();
          } else {
            StorageUtils.updateUser({proprietorId: ''});
            StorageUtils.removeStorageItem('proprietor');
            Control.replace('/xq/register', userInfo);
          }
        },
        function (error) {
          StorageUtils.updateUser({proprietorId: ''});
          StorageUtils.removeStorageItem('proprietor');
          alert('系统异常，请稍后重试。')
        }
      ).catch(function (reason) {
        alert('系统忙，请稍后重试。')
      });
    } else {
      Control.replace('/xq/register', userInfo);
      alert("请在微信中打开");
    }
  }

}
